package com.black.knight.chess;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.black.knight.chess.domain.Game;
import com.black.knight.chess.domain.PNGGame.PNGGames;
import com.black.knight.chess.enums.NewGame;
import com.black.knight.chess.model.PNGGamesModel;
import com.black.knight.chess.model.SahModel;
import com.black.knight.chess.utils.ChessUtil;
import com.black.knight.chess.utils.Utils;
import com.codethesis.pgnparse.PGNParseException;
import com.codethesis.pgnparse.PGNParser;

public class AddPGNGameActivity extends Activity{

	private AddPGNGameActivity context;
	
	Cursor cursor = null;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        
    	this.context = this;
    	
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.addpnggame);
        
        final EditText addGame = (EditText) findViewById(R.id.add_game);
        
        final EditText add_game_title = (EditText) findViewById(R.id.add_game_title);
        
        final Button add_game_button = (Button) findViewById(R.id.add_game_button);
        
        final Button show_game_button = (Button) findViewById(R.id.show_game_button);
        
        Map<String, String> tags = null;
        if(PNGGamesModel.getInstance().getTags() != null) {
        	tags = PNGGamesModel.getInstance().getTags();
        } else {
        	tags = SahModel.getInstance().getGame().getTags();
        }
        
	    addGame.setText(SahModel.getInstance().getGame().getPgnGameString());
	        
	    StringBuffer tagSaveString = new StringBuffer();
	        
        for (String key : tags.keySet()) {
            tagSaveString.append("[" + key + " " + "\"" + tags.get(key) + "\"]\n");
		}
        
        if(tagSaveString.toString().contains("]")) tagSaveString = new StringBuffer(tagSaveString.substring(0, tagSaveString.length() - 1));
        
        add_game_title.setText(tagSaveString);
        
        add_game_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					PGNParser.parseTags(add_game_title.getText().toString());
				} catch (PGNParseException e) {
					Utils.displayToastMessage(context, context.getResources().getString(R.string.error_parsing_tags));
					return;
				}
				
				String tagString = add_game_title.getText().toString();
				
				final ContentValues values = new ContentValues();
				values.put(PNGGames.CATEGORY, ChessUtil.getCategoryName(1));
				
				values.put(PNGGames.PNG, tagString + "\n" + addGame.getText().toString());
				
				values.put(PNGGames.FEN, SahModel.getInstance().getFenString());
				
				tagString = tagString.replace("[", "");
				tagString =	tagString.replace("]", "");
				tagString = tagString.replace("\"", "");
				
				String line;
				BufferedReader br = new BufferedReader(new StringReader(tagString));
				
				final StringBuffer stringBuffer = new StringBuffer();

				try {
					while ((line = br.readLine()) != null) {
						line = line.replaceFirst("[ ]", ": ");
						stringBuffer.append(line + "\n");
					}
				} catch (IOException e1) {
				}
				
				values.put(PNGGames.DESCRIPTION, stringBuffer.toString());
				
				try {
					PGNParser.parsePGNGame(values.getAsString(PNGGames.PNG), values.getAsString(PNGGames.FEN));
					
					Cursor cursor = PNGGamesModel.getGamesLike(PNGGames.DESCRIPTION + " = '" + stringBuffer.toString() + "'", ChessUtil.getCategoryName(1));
					if(cursor.getCount() > 0) {				    	
				    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
				    	builder.setMessage(context.getResources().getString(R.string.game_exist_replace))
				    	       .setPositiveButton(context.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
				    	           public void onClick(DialogInterface dialog, int id) {
				    	        	    SahModel.context.getContentResolver().delete(PNGGames.CONTENT_URI, PNGGames.DESCRIPTION + " = '" + stringBuffer.toString() + "'", null);
				    	        	   
				    	        	    SahModel.context.getContentResolver().insert(PNGGames.CONTENT_URI, values);
										
				    	        	    //publishGame(values);
				    	        	    
										Utils.displayToastMessage(context, context.getResources().getString(R.string.game_inserted_success));
										
										PNGGamesModel.getInstance().setTags(null);
										
										finish();
				    	           }
				    	       }).setNegativeButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
						           public void onClick(DialogInterface dialog, int id) {
						           }
						       });
				    	builder.create().show();
					} else {
						SahModel.context.getContentResolver().insert(PNGGames.CONTENT_URI, values);
						
    	        	    //publishGame(values);
						
						Utils.displayToastMessage(context, context.getResources().getString(R.string.game_inserted_success));
						
						PNGGamesModel.getInstance().setTags(null);
						
						finish();
					}
					
					cursor.close();
				} catch (Exception e) {
					Utils.displayToastMessage(context, context.getResources().getString(R.string.cannot_parse_pgn));
				}
			}
		});
        
        show_game_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					PNGGamesModel.getInstance().setCurrentGame(PGNParser.parsePGNGame(addGame.getText().toString(), SahModel.getInstance().getFenString()));
					
					PNGGamesModel.getInstance().setTags(PGNParser.parseTags(add_game_title.getText().toString()));
					
					PNGGamesModel.getInstance().getCurrentGame().setTags(PNGGamesModel.getInstance().getTags());
		    		
					String white = "White";
					String black = "Black";
					
					if(PNGGamesModel.getInstance().getCurrentGame().getTags().containsKey("White")) {
		    			white = PNGGamesModel.getInstance().getCurrentGame().getTags().get("White");
		    		}
					
					if(PNGGamesModel.getInstance().getCurrentGame().getTags().containsKey("Black")) {
		    			black = PNGGamesModel.getInstance().getCurrentGame().getTags().get("Black");
		    		}
		    		
		    		SahModel.getInstance().reset(SahModel.getInstance().getFenString());
	    	    	Game game = SahModel.getInstance().getGame();
	    	    	
	    	    	game.getPlayer1().setName(white);
	    	    	game.getPlayer2().setName(black);
	    	    	
	    	    	game.setMoves(PNGGamesModel.getInstance().getCurrentGame().toMoves());
	    	    	
					context.finish();
	    	    	
	    	    	SahModel.context.playNewGame(NewGame.ANALIZE, false);
				} catch (Exception e) {
					Utils.displayToastMessage(context, context.getResources().getString(R.string.cannot_parse_pgn));
				}
			}
		});
    }
    
    /*private void publishGame(ContentValues values) {
    	if(SettingsModel.getInstance().getLoggedUser() != null) {
	    	final EditText add_game_title = (EditText) findViewById(R.id.add_game_title);
	    	
	    	PublishGameCall call = new PublishGameCall(SahModel.context);
			if("my_games".equals(values.getAsString(PNGGames.CATEGORY))) {
				call.setCategory("MyGames-" + SettingsModel.getInstance().getLoggedUser().getUsername());
			} else {
				call.setCategory(values.getAsString(PNGGames.CATEGORY));
			}
			call.setPng(values.getAsString(PNGGames.PNG));
			call.setFen(values.getAsString(PNGGames.FEN));
			call.setDescription(add_game_title.getText().toString());
			
			SettingsModel.EXECUTOR_SERVICE.execute(call);
    	}
    }*/
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.addgame:
	        		        	
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
        }
    }
}